﻿<%@ WebHandler Language="C#" Class="ShowListServiceOver" %>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Data;
using Chenxin.Lib.Utility;
using Chenxin.Lib.Business;
using Chenxin.Lib.Business.BLL;

public class ShowListServiceOver : AjaxHandlerBase
{
    public ShowListServiceOver()
    {
        //核销
        htTypePermit.Add("over", Constants.Permit_Service_Over);
        //反核销
        htTypePermit.Add("unover", Constants.Permit_Service_UnOver);
        //导出
        htTypePermit.Add("export", Constants.Permit_Service_Export);
    }
    override public void RequestProcess(HttpContext context)
    {
        try
        {
            context.Response.ContentType = "text/plain";
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "");
            context.Response.CacheControl = "no-cache";

            string strOp = context.Request["op"];
            string strRet = string.Empty;
            switch (strOp.ToLower())
            {
                //获取信息
                case "getlist":
                    GetList(context);
                    break;
                case "getfwf":
                    GetFWF(context);
                    break;
                case "getbill":
                    GetBill(context);
                    break;
                case "over":
                    OverContract(context);
                    break;
                case "unover":
                    UnOverContract(context);
                    break;
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    private void GetList(HttpContext context)
    {
        try
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("a.ContractId in (select ContractId from dbo.t_ServiceCharge_BaseInfo where Status=1)");

            if(!string.IsNullOrEmpty(context.Request["keyword"]))
                sb.AppendFormat(" and (ContractCode like '%{0}%' or HouseAddress like '%{0}%') ", context.Request["keyword"]);

            if (!string.IsNullOrEmpty(context.Request["StartTime"]))
                sb.AppendFormat(" and ContractDate>='{0}' ", context.Request["StartTime"]);
            if (!string.IsNullOrEmpty(context.Request["EndTime"]))
                sb.AppendFormat(" and ContractDate<'{0}' ",DateTime.Parse(context.Request["EndTime"]).AddDays(1));
            if (!string.IsNullOrEmpty(context.Request["status"]))
            {
                string status = context.Request["status"];
                switch (status)
                {
                    case "10":
                        sb.Append(" and HasOver=1 ");
                        break;
                    case "20":
                        sb.Append(" and HasOver=0 and dbo.f_getServiceMoney(a.contractid,'')<=(dbo.f_getCommisionGeted(a.ContractId,'上家佣金','')+dbo.f_getCommisionGeted(a.ContractId,'下家佣金','')) ");
                        sb.Append(" and (VCommisionGeted+BCommisionGeted)>=(VRealCommisionFinal+BRealCommisionFinal)");
                        break;
                    case "30":
                        sb.Append(" and HasOver=0 and dbo.f_getServiceMoney(a.contractid,'')<=(dbo.f_getCommisionGeted(a.ContractId,'上家佣金','')+dbo.f_getCommisionGeted(a.ContractId,'下家佣金','')) ");
                        break;
                    case "40":
                        sb.Append(" and HasOver=0 and dbo.f_getServiceMoney(a.contractid,'')>(dbo.f_getCommisionGeted(a.ContractId,'上家佣金','')+dbo.f_getCommisionGeted(a.ContractId,'下家佣金','')) ");
                        break;
                }
            }

            //条件
            string strWhere = sb.ToString();
            //页码
            int strPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            //页显示行数
            int strPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 50 : int.Parse(context.Request["pagesize"]);//页记录数
            //欲选择字段列表 
            string FieldList = "ContractId,ContractDate,ContractCode,Departs,HouseAddress,VRealCommisionFinal,BRealCommisionFinal,VCommisionGeted,BCommisionGeted,fwf_count,"
                                + "vservicemoney,bservicemoney,vbillmoney,bbillmoney,bill_count,OverName,OverTime,HasOver";

            StringBuilder sbTableFieldList = new StringBuilder();
            sbTableFieldList.Append("a.ContractId,");
            sbTableFieldList.Append("CONVERT(Varchar(10),a.ContractDate,102) as ContractDate,ContractCode,dbo.f_get_contract_pointallot('Depart',a.ContractId,'All') AS Departs,HouseAddress,");
            sbTableFieldList.Append("VRealCommisionFinal,BRealCommisionFinal,VCommisionGeted,BCommisionGeted,dbo.f_getBillCount(a.ContractId,'1') as fwf_count,"
                + "dbo.f_getServiceMoney(a.ContractId,'上家佣金') as vservicemoney,dbo.f_getServiceMoney(a.ContractId,'下家佣金') as bservicemoney,"
                + "dbo.f_getCommisionGeted(a.ContractId,'上家佣金','') as vbillmoney,dbo.f_getCommisionGeted(a.ContractId,'下家佣金','') as bbillmoney,"
                + "dbo.f_getBillCount(a.ContractId,'0') as bill_count,OverName,OverTime,HasOver");

            //所要查询的表名
            string TableName = "t_Contract_BaseInfo a inner join t_Contract_CommisionInfo b On A.ContractId = b.ContractId ";
            //排序
            string strOrderField = "a.ContractDate desc";

            DataSet ds = Chenxin.Lib.Business.DAL.t_Contract_BaseInfo.GetList(strPageIndex, strPageSize, strOrderField, TableName, strWhere, FieldList, sbTableFieldList.ToString(), true);

            context.Response.Write(string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", ds.Tables[1].Rows[0][0], Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds.Tables[0])));             
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    private void GetFWF(HttpContext context)
    {
        string contractid = context.Request["contractid"];

        string strSql = "select * from t_ServiceCharge_BaseInfo where contractid='" + contractid + "' and Status=1";
        DataSet ds = Chenxin.Lib.Business.DAL.v_Contract_CommisionDetailInfo.GetList(strSql);

        context.Response.Write(string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", ds.Tables[0].Rows.Count, Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds.Tables[0])));
    }

    private void GetBill(HttpContext context)
    {
        string contractid = context.Request["contractid"];

        string strSql = "select * from t_Contract_Finance_BillInfo where contractid='" + contractid + "' and Status=1 and InOrOut=1 and IsFinish=1";
        DataSet ds = Chenxin.Lib.Business.DAL.v_Contract_CommisionDetailInfo.GetList(strSql);

        context.Response.Write(string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", ds.Tables[0].Rows.Count, Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds.Tables[0])));
    }

    private void OverContract(HttpContext context)
    {
        string modelid = context.Request["modelid"];
        if (!Chenxin.Lib.Business.DAL.ServiceChargeBaseInfo.CheckUnGet(modelid))
        {
            context.Response.Write("{success:0,msg:'该案有未收，无法进行核销操作！'}");
            return;
        }
        if (!Chenxin.Lib.Business.DAL.ServiceChargeBaseInfo.CheckServiceOver(modelid))
        {
            context.Response.Write("{success:0,msg:'该案状态不正常，无法进行核销操作！'}");
            return;
        }
        Chenxin.Lib.Business.Entity.t_Contract_BaseInfo info = Chenxin.Lib.Business.DAL.t_Contract_BaseInfo.GetModel(new Guid(modelid));
        info.HasOver = true;
        info.OverName = CurrentUserInfo.UserName;
        info.OverTime = DateTime.Now;
        Chenxin.Lib.Business.DAL.t_Contract_BaseInfo.Update(info);

        string text = CurrentUserInfo.UserName + "：服务费核销。合同编号：" + info.ContractCode;
        AddLog(text, BusinessType.BusinessTypeComboList()["OprType_OverService"].ToString());

        context.Response.Write("{success:1,msg:'核销成功！',data:''}");
    }
    
    private void UnOverContract(HttpContext context)
    {
        string modelid = context.Request["modelid"];
        Chenxin.Lib.Business.Entity.t_Contract_BaseInfo info = Chenxin.Lib.Business.DAL.t_Contract_BaseInfo.GetModel(new Guid(modelid));
        info.HasOver = false;
        info.OverName = "";
        info.OverTime = null;
        Chenxin.Lib.Business.DAL.t_Contract_BaseInfo.Update(info);

        string text = CurrentUserInfo.UserName + "：服务费反核销。合同编号：" + info.ContractCode;
        AddLog(text, BusinessType.BusinessTypeComboList()["OprType_UnOverService"].ToString());

        context.Response.Write("{success:1,msg:'反核销成功！',data:''}");
    }
}